package study.io.springboot.upload.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import study.eggs.result.Result;
import study.eggs.result.Results;

import java.io.File;
import java.io.InputStream;


/**
 * https://cloud.tencent.com/document/product/436
 * https://www.alibabacloud.com/help/zh/oss/?spm=a2c63.l28256.0.0.6cca4b78DsdR9p
 */
@Slf4j
@RestController
@RequestMapping("/oss")
public class _3_OSSController {

    @Autowired
    private OSSClient ossClient;
    @Value("${aliyun.oss.bucketName: }")
    private String bucketName;

    /**
     * 1.put 流 InputStream
     * 2.put 文件 File
     */
    @RequestMapping("/put2Oss")
    public Result put2Oss(@RequestParam("file") MultipartFile file) {
        //临时文件
        File tempFile = FileUtil.newFile(IdUtil.fastSimpleUUID());
        try (InputStream is = file.getInputStream()) {
            //保存临时文件
            FileUtil.writeFromStream(is, tempFile);

            String key = StrUtil.format("test/{}.{}", IdUtil.fastSimpleUUID(), "");
            PutObjectResult result = ossClient.putObject(bucketName, key, tempFile);
            log.info("{}", result.getResponse());
        } catch (Exception ex) {
            throw new RuntimeException("上传文件异常: ", ex);
        } finally {
            //清理临时文件
            FileUtil.del(tempFile);
        }
        return Results.ok();
    }

    /**
     * 1. get 流 InputStream
     * 2. get 文件 File
     */
    @RequestMapping("/getFromOss")
    public Result getFromOss(@RequestParam("key") String key) {
        //
        GetObjectRequest request = new GetObjectRequest(bucketName, key);
        OSSObject ossObject = ossClient.getObject(request);
        try (InputStream is = ossObject.getObjectContent()) {

        } catch (Exception ex) {
            throw new RuntimeException("上传文件异常: ", ex);
        }
        return Results.ok();
    }
}
